<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="$t('calling.loginName')" prop="loginName">
        <el-input
          v-model="queryParams.loginName"
          :placeholder="$t('calling.loginNameInput')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('calling.peopleName')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('calling.peopleNameInput')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('program.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="$t('equipment.statusSelect')"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('elButton.establishTime')">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          :start-placeholder="$t('elButton.startTime')"
          :end-placeholder="$t('elButton.endTime')"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("elButton.search") }}
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("elButton.reset")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['staff_add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >{{ $t("elButton.add") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['staff_edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
          >{{ $t("elButton.change") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['staff_del']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDel"
          >{{ $t("elButton.delete") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['staff_export']"
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >{{ $t("elButton.import") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPerm="['staff_export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >{{ $t("elButton.export") }}
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-user"
          size="mini"
          @click="handleBatchUpload"
          >{{ $t("elButton.batchUpload") }}
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip
          class="item"
          effect="dark"
          :content="$t('elButton.refresh')"
          placement="top"
        >
          <el-button
            size="mini"
            circle
            icon="el-icon-refresh"
            @click="handleQuery"
          />
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          :content="
            showSearch ? $t('elButton.hideSearch') : $t('elButton.showSearch')
          "
          placement="top"
        >
          <el-button
            size="mini"
            circle
            icon="el-icon-search"
            @click="showSearch = !showSearch"
          />
        </el-tooltip>
      </div>
    </el-row>

    <el-table
      v-loading="loading"
      :data="staffList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        :label="$t('equipment.number')"
        width="55"
        align="center"
        prop="id"
      />
      <el-table-column
        :label="$t('calling.loginName')"
        align="center"
        prop="loginName"
      />
      <el-table-column
        :label="$t('calling.peopleName')"
        align="center"
        prop="name"
      />
      <el-table-column
        :label="$t('calling.sex')"
        align="center"
        prop="sex"
        :formatter="sexFormat"
      />
      <el-table-column
        :label="$t('calling.style')"
        align="center"
        prop="occupation"
        :formatter="occupationFormat"
      />
      <el-table-column :label="$t('calling.star')" align="center" prop="rate" />
      <el-table-column
        :label="$t('calling.title')"
        align="center"
        prop="ranks"
      />
      <el-table-column
        :label="$t('program.status')"
        align="center"
        prop="status"
        :formatter="statusFormat"
      />
      <el-table-column
        :label="$t('elButton.establishTime')"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('equipment.control')"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPerm="['staff_edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            >{{ $t("elButton.change") }}
          </el-button>
          <el-button
            v-hasPerm="['staff_del']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
            >{{ $t("elButton.delete") }}
          </el-button>
          <el-button
            v-hasPerm="['user_reset']"
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPwd(scope.row)"
            >{{ $t("elButton.reset") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改工作人员对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('calling.loginName')" prop="loginName">
              <el-input
                v-model="form.loginName"
                :placeholder="$t('calling.loginNameInput')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('calling.peopleName')" prop="name">
              <el-input
                v-model="form.name"
                :placeholder="$t('calling.docterNameInput')"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="!form.id" :span="12">
            <el-form-item :label="$t('password')" prop="password">
              <el-input
                v-model="form.password"
                type="password"
                show-password="true"
                :placeholder="$t('passwordInput')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('calling.department')" prop="deptId">
              <treeselect
                v-model="form.deptId"
                @input="inputSelect"
                :options="deptOptions"
                :normalizer="normalizer"
                :default-expand-level="2"
                :placeholder="$t('calling.departmentInput')"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('calling.position')" prop="occupation">
              <el-select v-model="form.occupation">
                <el-option
                  v-for="dict in occupationOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('calling.title')" prop="ranks">
              <el-input
                v-model="form.ranks"
                :placeholder="$t('calling.titleInput')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('calling.sex')" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio
                  v-for="dict in sexOptions"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('role.role')" prop="roles">
              <el-select
                v-model="form.roles"
                multiple
                :placeholder="$t('role.choose')"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.status == 1"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('calling.avatr')" prop="portrait">
              <el-upload
                ref="upload"
                class="avatar-uploader"
                :auto-upload="true"
                :headers="{
                  Authorization: 'Bearer ' + getAccessToken(),
                }"
                :action="`${VUE_APP_BASE_API}/common/upload`"
                :show-file-list="false"
                :on-success="handleOnSuccess"
                :on-error="handleOnError"
              >
                <img
                  v-if="form.portrait"
                  :src="`${VUE_APP_BASE_API}` + form.portrait"
                  class="avatar"
                />
                <img v-else :src="`/img/shangchuan_icon@2x.png`" />
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('calling.star')" prop="rate">
              <el-rate v-model="form.rate" :allow-half="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('calling.synopsis')" prop="introduce">
              <el-input
                v-model="form.introduce"
                type="textarea"
                :placeholder="$t('calling.synopsisInput')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("submitText")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancelText") }}</el-button>
      </div>
    </el-dialog>
    <!--    修改密码-->
    <el-dialog
      :title="$t('profile.resetPwd')"
      :visible.sync="resetStatus"
      width="20%"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('profile.newPassword')" prop="newPassword">
              <el-input
                v-model="form.newPassword"
                :placeholder="$t('profile.newPasswordInput')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleResetPwdSure">{{
          $t("submitText")
        }}</el-button>
        <el-button @click="resetStatus = false">{{
          $t("cancelText")
        }}</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      :modal-append-to-body="true"
      :append-to-body="true"
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          {{ $t("edition.uploadDrop") }}<em>{{ $t("edition.uploadClick") }}</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          <el-checkbox v-model="upload.updateSupport" />
          {{ $t("edition.isUpdate") }}
          <el-link type="info" style="font-size:12px" @click="importTemplate"
            >{{ $t("edition.downLoadTemplate") }}
          </el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">
          {{ $t("edition.importWarning") }}
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">{{
          $t("submitText")
        }}</el-button>
        <el-button @click="upload.open = false">{{
          $t("cancelText")
        }}</el-button>
      </div>
    </el-dialog>

    <!-- 导入批量上传对话框 -->
    <el-dialog
      :title="uploadLogo.title"
      :visible.sync="uploadLogo.open"
      width="800px"
      :modal-append-to-body="true"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <div style="padding: 0px 5px;">
        <span style="float: left;">
          <el-button
            style="width: 100px;"
            type="primary"
            :disabled="visibleCheckPicture"
            @click="submitUpload"
            >{{ $t("profile.upload") }}</el-button
          >
        </span>
        <div style="float: right;">
          <el-button :disabled="visibleChoosePicture" @click="deletePicture"
            >清空</el-button
          >
        </div>
        <div style="float: right;padding: 0 10px 0 5px;">
          <el-button :disabled="visibleChoosePicture" @click="checkPicture"
            >校验</el-button
          >
        </div>
        <el-upload
          style="float: right;padding: 0 5px 0 0;"
          ref="uploadLogo"
          action="action没有任何意义，因为已经重写了http-request"
          multiple
          accept=".zip, .png, .jpg"
          :on-change="selectPicture"
          :auto-upload="false"
          :show-file-list="false"
          :http-request="submitUpload"
        >
          <el-button slot="trigger" size="small">选择图片</el-button>
        </el-upload>
      </div>
      <div style="padding: 55px 5px;">
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column align="center" prop="name" label="图片名称">
          </el-table-column>
          <el-table-column align="center" prop="schedule" label="上传进度">
          </el-table-column>
          <el-table-column align="center" prop="state" label="上传进度">
          </el-table-column>
          <el-table-column align="center" prop="result" label="校验结果">
          </el-table-column>
          <el-table-column align="center" prop="illustrate" label="说明">
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="120"
          >
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.$index, tableData)"
                type="text"
                size="small"
              >
                <i class="el-icon-error"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="color: red;padding: 0px 5px;">
        <div>*注意事项：</div>
        <div>1、仅支持上传PNG、ZIP、jpg格式文件;</div>
        <div>2、请以医生编号作为图片名称，图片大小要小于2MB;</div>
        <div>3、选择图片后请先点击检查，校验图片是否符合要求;</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  resetPwd,
  listStaff,
  getStaff,
  delStaff,
  addStaff,
  editStaff,
  exportStaff,
  importTemplate,
  batchUploadPic,
} from "@/api/qbs/staff";
import { getAccessToken } from "@/data/user";
import { deptTree } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getUser } from "@/api/system/user";
import JSZip from "jszip";
let timer = null; // 防抖

export default {
  name: "Staff",
  components: { Treeselect },
  data() {
    return {
      //密码对话框
      resetStatus: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      resetId: "",
      // 总条数
      total: 0,
      // 工作人员表格数据
      staffList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 机构名称树选项
      deptOptions: [],
      // 状态,性别，职业字典
      statusOptions: [],
      sexOptions: [],
      occupationOptions: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        loginName: undefined,
        name: undefined,
        status: undefined,
        createTime: undefined,
      },
      // 显示搜索条件
      showSearch: true,
      // 表单参数
      form: {},
      roleOptions: [],
      // 表单校验
      rules: {
        loginName: [
          {
            required: true,
            message: this.$t("loginNameEmpty"),
            trigger: "blur",
          },
        ],
        newPassword: [
          {
            required: true,
            message: this.$t("role.newPasswordInput"),
            trigger: "blur",
          },
          { min: 6, message: this.$t("lessPassword"), trigger: "blur" },
        ],
        name: [
          { required: true, message: this.$t("nameEmpty"), trigger: "blur" },
        ],
        occupation: [
          {
            required: true,
            message: this.$t("positionEmpty"),
            trigger: "change",
          },
        ],
        /* portrait: [
            { required: true, message: "头像不能为空", trigger: "blur" }
          ],*/
        password: [
          {
            required: true,
            message: this.$t("passwordEmpty"),
            trigger: "blur",
          },
        ],
        ranks: [
          {
            required: true,
            message: this.$t("calling.titleEmpty"),
            trigger: "blur",
          },
        ],
        deptId: [
          {
            required: true,
            message: this.$t("calling.departmentEmpty"),
            trigger: "blur",
          },
        ],
        roles: [
          {
            required: true,
            message: this.$t("calling.roleEmpty"),
            trigger: "blur",
          },
        ],
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getAccessToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/qbs/staff/import",
      },
      // 批量上传头像参数
      uploadLogo: {
        // 是否显示弹出层（批量上传头像）
        open: false,
        // 弹出层标题（批量上传头像）
        title: "",
      },
      tableData: [],
      filesData: [],
      visibleChoosePicture: true,
      visibleCheckPicture: true,
      VUE_APP_BASE_API: process.env.VUE_APP_BASE_API,
      getAccessToken,
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getDicts("status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("occupation").then((response) => {
      this.occupationOptions = response.data;
    });
  },
  methods: {
    inputSelect() {
      this.$refs.form.validateField("deptId");
    },
    /** 查询工作人员列表 */
    getList() {
      this.loading = true;
      listStaff(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.staffList = response.data;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.reset();
      this.resetStatus = true;
      this.resetId = row.id;
    },
    /** 重置密码按钮操作 */
    handleResetPwdSure() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          resetPwd(this.resetId, this.form.newPassword).then((response) => {
            if (response.code === 0) {
              this.resetStatus = false;
              this.msgSuccess(
                this.$t("profile.changePswRight") + this.form.newPassword
              );
            } else {
              this.msgError(response.msg);
            }
          });
        }
      });
    },
    /** 查询机构名称下拉树结构 */
    getDeptTree() {
      deptTree().then((response) => {
        if (response.data && response.data.length > 0) {
          this.deptOptions = this.handleTree(
            response.data,
            "deptId",
            "parentId",
            "children",
            response.data[0].parentId
          );
        } else {
          this.deptOption = [];
        }
      });
    },
    /** 转换机构数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.name,
        children: node.children,
      };
    },

    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 性别字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex);
    },
    // 职业类型字典翻译
    occupationFormat(row, column) {
      return this.selectDictLabel(this.occupationOptions, row.occupation);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        loginName: undefined,
        name: undefined,
        password: undefined,
        portrait: undefined,
        rate: 5,
        ranks: undefined,
        introduce: undefined,
        deptId: undefined,
        status: "0",
        occupation: undefined,
        sex: "0",
      };
      this.$nextTick(() => {
        this.$refs.upload.clearFiles();
      });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getUser().then((response) => {
        this.roleOptions = response.data.extend;
        this.open = true;
      });
      this.title = this.$t("calling.wordPeopleAdd");
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset();
      const id = row.id || this.ids;
      getUser().then((response) => {
        this.roleOptions = response.data.extend;
        getStaff(id).then((response) => {
          this.form = response.data;
          this.form.rate = Number(this.form.rate);
          this.form.roles = response.data.roles || [];
          this.open = true;
          this.title = this.$t("calling.wordPeopleChange");
        });
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // this.$refs.upload.submit();
          if (this.form.id !== undefined) {
            editStaff(this.form).then((response) => {
              if (response.code === 0) {
                this.msgSuccess(this.$t("loginLog.changeSuccess"));
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addStaff(this.form).then((response) => {
              if (response.code === 0) {
                this.msgSuccess(this.$t("addSuccess"));
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    // 上传成功
    handleOnSuccess(res, rawFile) {
      if (res.code === 1) {
        this.$message({
          type: "error",
          message: res.msg,
          showClose: true,
        });
      } else {
        this.$message({
          message: this.$t("uploadSuccess"),
          type: "success",
          showClose: true,
        });
        this.form.portrait = res.data;
      }
    },
    // 上传失败
    handleOnError() {
      this.open = false;
      this.$message({
        message: this.$t("edition.uploadFail"),
        type: "error",
        showClose: true,
      });
    },
    /** 删除按钮操作 */
    handleDel(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        this.$t("calling.wordPeopleDelete") +
          ids +
          this.$t("equipment.deleteEquipment2"),
        this.$t("warning"),
        {
          confirmButtonText: this.$t("submitText"),
          cancelButtonText: this.$t("cancelText"),
          type: "warning",
        }
      )
        .then(function() {
          return delStaff(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess(this.$t("deleteSuccess"));
        })
        .catch(function() {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = this.$t("elButton.import");
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.data);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.data, this.$t("elButton.importResult"), {
        dangerouslyUseHTMLString: true,
      });
      this.getList();
    },
    handleFileError(err, file, fileList) {
      this.msgError(err);
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.ids.length === 0) {
        this.msgWarning(this.$t("equipment.equipmentInput"));
        return;
      }
      const queryParams = this.queryParams;
      this.$confirm(this.$t("calling.wordPeopleExport"), this.$t("warning"), {
        confirmButtonText: this.$t("submitText"),
        cancelButtonText: this.$t("cancelText"),
        type: "warning",
      })
        .then(() => {
          return exportStaff(queryParams, this.ids);
        })
        .then((response) => {
          this.download(response.data);
        })
        .catch(function() {});
    },
    // 关闭窗体
    handleClose() {
      // 清除数据
      this.deletePicture();
      this.uploadLogo.open = false;
    },
    /** 批量上传头像按钮操作 */
    handleBatchUpload() {
      this.uploadLogo.title = this.$t("elButton.batchUpload");
      this.uploadLogo.open = true;
    },
    // 去重代码，索引大的覆盖索引小的，关键字段为图片名称name
    deduplicateArray(arr) {
      const uidIndexMap = {};
      const deduplicatedArr = [];
      for (let i = 0; i < arr.length; i++) {
        const element = arr[i];
        const name = element.name;
        if (!(name in uidIndexMap)) {
          uidIndexMap[name] = i;
          deduplicatedArr[i] = element;
        } else {
          const existingIndex = uidIndexMap[name];
          if (i > existingIndex) {
            uidIndexMap[name] = i;
            deduplicatedArr[existingIndex] = element;
          }
        }
      }
      return deduplicatedArr;
    },
    // 选择图片
    async selectPicture(file) {
      console.log(`file.raw.type`,file.raw.type)
      if (file.raw.type == "image/png" || file.raw.type == "image/jpeg"|| file.raw.type == "image/jpg") {
        let name = file.name.slice(0, -4);
        this.tableData.push({
          uid: file.uid,
          name: name,
          schedule: "0%",
          state: "等待上传",
          result: <i class="el-icon-warning" />,
          illustrate: "",
        });
        // 存储文件
        this.filesData.push(file.raw);
      } else if (file.raw.type == "application/x-zip-compressed") {
        this.unZip(file.raw);
      }
      // 开启校验按钮(延迟适应压缩包解压)
      setTimeout(() => {
        // 检验去重并排序
        this.filesData = this.sort(this.deduplicateArray(this.filesData));
        this.tableData = this.sort(this.deduplicateArray(this.tableData));
        if (this.filesData.length > 0 || this.tableData.length > 0) {
          this.visibleChoosePicture = false;
          this.visibleCheckPicture = true;
        }
      }, 500);
    },
    // 排序
    sort(arr) {
      arr.sort(function(a, b) {
        var nameA = parseInt(a.name);
        var nameB = parseInt(b.name);
        // 如果nameA小于nameB，返回一个负数
        if (nameA < nameB) {
          return -1;
        }
        // 如果nameA大于nameB，返回一个正数
        if (nameA > nameB) {
          return 1;
        }
        // 如果nameA等于nameB，返回0
        return 0;
      });
      return arr;
    },
    // 解压 .zip 文件
    async unZip(zipFile) {
      console.log(`zipFile`,zipFile)
      var that = this;
      // 判断是否是 .zip 文件
      let isZipFile = zipFile.type === "application/x-zip-compressed";
      if (!isZipFile) {
        return;
      }
      const zip = new JSZip();
      // 解压Zip压缩包，参数默认是二进制
      const zipData = await zip.loadAsync(zipFile);
      console.log(`zipData`,zipData)
      zipData.forEach(function(relativePath, file) {
        // fix: 过滤 mac osx 系统压缩的副作用
        if (!relativePath.startsWith("__MACOSX")) {
          // 判断是否是目录
          if (!file.dir && !file.name.includes("/")) {
            zip
              .file(file.name)
              .async("uint8array")
              .then(function(u8) {
                // 创建 File 对象的
                let blob = new File([u8], file.name);

                that.tableData.unshift({
                  uid: file.uid,
                  name: file.name.slice(0, -4),
                  schedule: "0%",
                  state: "等待上传",
                  result: <i class="el-icon-warning" />,
                  illustrate: "",
                });
                that.filesData.unshift(blob);
              });
          } else {
            // timer 防抖动
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
              that.$notify.error({
                title: "错误",
                message: "该压缩包存在下级目录层级！",
                duration: 2000,
              });
            }, 1000);
          }
        }
      });
    },
    // 校验
    checkPicture() {
      console.log(`this.tableData`,this.tableData)
      console.log(`this.filesData`,this.filesData)
      for (let index in this.tableData) {
        let deleteAction = false;
        for (let key in this.filesData) {
          const fileData = this.filesData[key];
          if (fileData.uid == this.tableData[index].uid) {
            console.log(`fileData.name.slice(0, -4)`,fileData.name.slice(0, -4),Number(fileData.name.slice(0, -4)))
            if (!Number(fileData.name.slice(0, -4))) {
              this.tableData[key].result = <i class="el-icon-error" />;
              this.tableData[key].illustrate = "图片名称需为医生编号";
              deleteAction = true;
            } else if (fileData.size >= 2000000) {
              this.tableData[key].result = <i class="el-icon-error" />;
              this.tableData[key].illustrate = "图片大小>2MB";
              deleteAction = true;
            } else {
              this.tableData[key].result = <i class="el-icon-success" />;
            }
          }
        }
        if (deleteAction) {
          this.filesData = this.filesData.filter(
            (file) => file.uid !== this.tableData[index].uid
          );
        }
      }
      this.visibleCheckPicture = false;
    },
    deletePicture() {
      // 清除数据
      this.tableData = [];
      this.filesData = [];
      this.visibleCheckPicture = true;
      this.visibleChoosePicture = true;
    },
    // 移除本行数据
    deleteRow(index, rows) {
      rows.splice(index, 1);
      this.filesData.splice(index, 1);
    },
    // 上传
    submitUpload() {
      let filesData = this.filesData;
      for (let key in filesData) {
        this.uploadPicture(filesData[key]);
      }
      // 再次校验并删除表单数据
      for (let key in this.tableData) {
        if (this.tableData[key].result.data.class == "el-icon-error") {
          this.deleteRow(key, this.tableData);
          // timer 防抖动
          if (timer) clearTimeout(timer);
          timer = setTimeout(() => {
            this.$notify.error({
              title: "错误",
              message: "存在校验不通过的图片，请进行修改，再重新上传",
              duration: 2000,
            });
          }, 1000);
        }
      }
      // 上传结束全部置灰（除选择和清空）
      this.visibleChoosePicture = true;
      this.visibleCheckPicture = true;
    },
    async uploadPicture(file) {
      var that = this;
      const formData = new FormData();
      formData.append("file", file);
      // 批量上传头像
      batchUploadPic(formData).then((response) => {
        if (response.code == 0) {
          editStaff({
            id: Number(file.name.slice(0, -4)),
            portrait: response.data,
          })
            .then((res) => {
              if (res.code == 0) {
                for (let key in that.tableData) {
                  if (that.tableData[key].name == file.name.slice(0, -4)) {
                    that.tableData[key].schedule = "100%";
                    that.tableData[key].state = "上传完成";
                    // that.tableData[key].result = <i class="el-icon-success" />;
                    that.tableData[key].illustrate = "";
                  }
                }
              }
            })
            .catch((error) => {
              for (let key in that.tableData) {
                if (that.tableData[key].name == file.name.slice(0, -4)) {
                  that.tableData[key].schedule = "0%";
                  that.tableData[key].state = "上传失败";
                  // that.tableData[key].result = <i class="el-icon-error" />;
                  that.tableData[key].illustrate = error.message;
                }
              }
              // timer 防抖动
              if (timer) clearTimeout(timer);
              timer = setTimeout(() => {
                that.$notify.error({
                  title: "错误",
                  message: "图片上传失败，请重试",
                  duration: 2000,
                });
              }, 1000);
            });
        }
      });
    },
  },
};
</script>
<style scoped>
.el-rate {
  line-height: 2;
}
</style>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
